#include "head.h"

int local_send(int local_fd, int sock_fd)
{
    struct msghdr msg;
    bzero(&msg, sizeof(msg));

    char str[6] = "hello";
    struct iovec iove[1];
    iove[0].iov_base = str;
    iove[0].iov_len = strlen(str);
    msg.msg_iov = iove;
    msg.msg_iovlen = 1;


    struct cmsghdr* pcms = (struct cmsghdr*)malloc(CMSG_LEN(sizeof(int)));
    pcms->cmsg_len = CMSG_LEN(sizeof(int));
    pcms->cmsg_level = SOL_SOCKET;
    pcms->cmsg_type = SCM_RIGHTS;
    void *addr = CMSG_DATA(pcms);
    int *p_fd = (int *)addr;
    *p_fd = sock_fd;

    msg.msg_control = pcms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    sendmsg(local_fd,&msg, 0);

    return 0;
}

int local_recv(int local_fd, int* sock_fd)
{
    /*
    struct msghdr hdr;
    bzero(&hdr, sizeof(hdr));

    char buf[60] = {0};
    struct iovec vec[1];
    vec[0].iov_base = buf;
    vec[0].iov_len = sizeof(buf);

    hdr.msg_iov = vec;
    hdr.msg_iovlen = 1;

    struct cmsghdr *pcms = (struct cmsghdr *)malloc(CMSG_LEN(sizeof(int)));
    pcms->cmsg_len = CMSG_LEN(sizeof(int));
    pcms->cmsg_level = SOL_SOCKET;
    pcms->cmsg_type = SCM_RIGHTS;

    hdr.msg_control = pcms;
    hdr.msg_controllen = CMSG_LEN(sizeof(int));

    recvmsg(local_fd,&hdr, 0);

    void *addr = CMSG_DATA(pcms);
    *sock_fd = (int *)addr;
    return 0;
    */
   struct msghdr msg;// 控制本地socket发送的数据
    memset(&msg, 0, sizeof(msg));

    // 正文信息
    char buf[60] = {0};
    struct iovec iov[1];
    iov[0].iov_base = buf;
    iov[0].iov_len = sizeof(buf);

    msg.msg_iov = iov;
    msg.msg_iovlen =1;


    // 控制信息 
    struct cmsghdr *cms = (struct cmsghdr *) malloc( CMSG_LEN(sizeof(int)) );
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;


    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    // 接收数据: 从本地socket
    recvmsg(local_fd, &msg, 0);

    void *p =  CMSG_DATA(cms);
    int *fd = (int *)p;

    *sock_fd = *fd;

    return 0;
}
